//
//  WBKeyboard.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/18.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

fileprivate let identifier = "cells"

class WBKeyboard: UIView {
    /// 初始化数据源
    var dataSourceArr: [[[WBEmotionModel]]] = WBEmotionTool().dataSourceArr

    /// 键盘的collectionView
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: screenWidth, height: 271-37)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(WBKeyboardCell.self, forCellWithReuseIdentifier: identifier)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        
        return collectionView
    
    }()
    
    /// pageControl
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.numberOfPages = self.dataSourceArr[0].count
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.isEnabled = false
        return pageControl
    }()
    
    /// 底部的toolBar
    lazy var toolBar: WBKeyboardToolbar = {
        let bar = WBKeyboardToolbar()
        bar.delegate = self
        return bar
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 设置UI
extension WBKeyboard {
    func setupUI () {
        //1. 添加子视图
        addSubview(collectionView)
        addSubview(pageControl)
        addSubview(toolBar)
        
        //2. 设置子视图
        collectionView.backgroundColor = UIColor.white
        toolBar.backgroundColor = UIColor.gray
        
        //3. 自动布局
        collectionView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.bottom.equalTo(self).offset(-37)
        }
        
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-40)
        }
        
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(37)
        }
    }
}

// MARK: - UICollectionViewDataSource
extension WBKeyboard: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataSourceArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSourceArr[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! WBKeyboardCell
        
        //cell.backgroundColor = UIColor.randomColor()
        
        //获取表情
        let cellData = dataSourceArr[indexPath.section][indexPath.item]
        cell.models = cellData
        
//        //先把cell上的测试label先移除
//        cell.contentView.viewWithTag(100)?.removeFromSuperview()
//        
//        //再创建测试用的label
//        let testLabel = UILabel(text: "section:\(indexPath.section), item:\(indexPath.item)", textColor: UIColor.black, fontSize: 35, alignment: .center)
//        testLabel.tag = 100
//        cell.contentView.addSubview(testLabel)
//        testLabel.sizeToFit()
//        testLabel.center = cell.contentView.center
        
        return cell
    }
}

// MARK: - 事件处理
extension WBKeyboard {
    //设置pageControl
    func setPageControl(indexPath: IndexPath) {
        //当前的section有几个cell，pageControl就显示几个点
        let numOfPages = dataSourceArr[indexPath.section].count
        pageControl.numberOfPages = numOfPages
        pageControl.currentPage = indexPath.item
    }
}


// MARK: - toobar的点事件的代理
extension WBKeyboard: WBKeyboardToolbarDelegate {
    func changeKeyboard(index: Int) {
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        //设置pageControl
        setPageControl(indexPath: indexPath)
    }
}


// MARK: - UICollectionViewDelegate
extension WBKeyboard: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //判断当前是哪个section
        /*
         1. 在屏幕上，最多可以同时显示两个cell，哪个cell显示的区域较大，说明现在是哪个cell所在的section
         2. 意味着需拿到显示在屏幕上的cell；并计算它们在屏幕上的显示区域
         3. 怎么拿到显示在屏幕上的cell： collectionView.visibleCells
         4. 怎么计算cell在屏幕上的显示区域： 相邻的两个cell，|cell.origin.x - offset.x|绝对值越小，说明该cell在屏幕上的显示区域越大
        */
        let cells = collectionView.visibleCells
        let offsetx = scrollView.contentOffset.x
        if cells.count > 1 {
            let cell1 = cells[0]
            let outRegion = abs(cell1.frame.origin.x - offsetx)
            
            let cell2 = cells[1]
            let outRegion2 = abs(cell2.frame.origin.x - offsetx)
            
            if outRegion < outRegion2 {
                //说明使用第一个cell的section
                let indexPath1 = collectionView.indexPath(for: cell1)
                toolBar.index = indexPath1!.section
                setPageControl(indexPath: indexPath1!)
            } else {
                //说明使用第二个cell的section
                let indexPath2 = collectionView.indexPath(for: cell2)
                toolBar.index = indexPath2!.section
                setPageControl(indexPath: indexPath2!)
            }
        }
    }
}
